<template>
  <div class="literature-upload">
    <div class="header">
      <h2>上传文献</h2>
    </div>

    <el-alert
      v-if="userStore.userType === 2"
      title="管理员不能上传文献"
      type="error"
      description="您当前是管理员账户，无法上传文献。请使用普通用户账户进行上传操作。"
      show-icon
      closable
      style="margin-bottom: 20px;"
    />

    <el-form 
      v-else
      ref="uploadForm" 
      :model="form" 
      :rules="rules" 
      label-width="120px"
      class="upload-form"
    >
      <!-- 基本信息 -->
      <el-card class="form-card">
        <template #header>
          <h3>基本信息</h3>
        </template>
        
        <el-form-item label="文献标题" prop="title">
          <el-input 
            v-model="form.title" 
            placeholder="请输入文献标题"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="作者" prop="authors">
          <el-input 
            v-model="form.authors" 
            placeholder="请输入作者，多个作者用逗号分隔"
            maxlength="100"
          />
        </el-form-item>

        <el-form-item label="发表日期" prop="publicationDate">
          <el-date-picker
            v-model="form.publicationDate"
            type="date"
            placeholder="请选择发表日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="期刊名称">
          <el-input 
            v-model="form.journal" 
            placeholder="请输入期刊名称"
            maxlength="100"
          />
        </el-form-item>

        <el-form-item label="关键词" prop="keywords">
          <el-input 
            v-model="form.keywords" 
            placeholder="请输入关键词，多个关键词用逗号分隔"
            maxlength="200"
          />
        </el-form-item>

        <el-form-item label="摘要">
          <el-input 
            v-model="form.abstractText" 
            type="textarea" 
            :rows="4"
            placeholder="请输入文献摘要"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
      </el-card>

      <!-- 文件上传 -->
      <el-card class="form-card">
        <template #header>
          <h3>文件上传</h3>
        </template>

        <el-form-item label="文件类型" prop="fileType">
          <el-radio-group v-model="form.fileType">
            <el-radio label="pdf">PDF文档</el-radio>
            <el-radio label="doc">Word文档</el-radio>
            <el-radio label="image">图片文件</el-radio>
            <el-radio label="text">纯文本</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="文献文件" prop="file">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            :limit="1"
            :accept="getAcceptTypes()"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                {{ getUploadTip() }}
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-card>

      <!-- 智能识别选项 -->
      <el-card class="form-card">
        <template #header>
          <h3>智能识别选项</h3>
        </template>

        <el-form-item label="启用OCR识别">
          <el-switch 
            v-model="form.enableOCR" 
            active-text="开启" 
            inactive-text="关闭"
          />
          <div class="help-text">
            开启后将自动识别图片和PDF中的文字内容
          </div>
        </el-form-item>

        <el-form-item label="关键词提取">
          <el-switch 
            v-model="form.enableKeywordExtraction" 
            active-text="开启" 
            inactive-text="关闭"
          />
          <div class="help-text">
            开启后将自动从文档内容中提取关键词
          </div>
        </el-form-item>

        <el-form-item label="内容摘要">
          <el-switch 
            v-model="form.enableSummary" 
            active-text="开启" 
            inactive-text="关闭"
          />
          <div class="help-text">
            开启后将自动生成文档内容摘要
          </div>
        </el-form-item>
      </el-card>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          {{ submitting ? '上传中...' : '提交上传' }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { literatureApi } from '@/api/literature'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const uploadForm = ref()
const uploadRef = ref()
const submitting = ref(false)
const fileList = ref([])

const form = reactive({
  title: '',
  authors: '',
  publicationDate: '',
  journal: '',
  keywords: '',
  abstractText: '',
  fileType: 'pdf' as 'pdf' | 'doc' | 'image' | 'text',
  file: null as File | null,
  enableOCR: true,
  enableKeywordExtraction: true,
  enableSummary: true
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入文献标题', trigger: 'blur' },
    { min: 2, max: 200, message: '标题长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  authors: [
    { required: true, message: '请输入作者', trigger: 'blur' },
    { max: 100, message: '作者长度不能超过 100 个字符', trigger: 'blur' }
  ],
  publicationDate: [
    { required: true, message: '请选择发表日期', trigger: 'change' }
  ],
  keywords: [
    { required: true, message: '请输入关键词', trigger: 'blur' },
    { max: 200, message: '关键词长度不能超过 200 个字符', trigger: 'blur' }
  ],
  fileType: [
    { required: true, message: '请选择文件类型', trigger: 'change' }
  ]
}

// 方法
const getAcceptTypes = () => {
  const acceptTypes: Record<string, string> = {
    pdf: '.pdf',
    doc: '.doc,.docx',
    image: '.jpg,.jpeg,.png,.bmp,.gif',
    text: '.txt,.rtf'
  }
  return acceptTypes[form.fileType] || '*'
}

const getUploadTip = () => {
  const tips: Record<string, string> = {
    pdf: '只能上传PDF文件，且不超过20MB',
    doc: '只能上传Word文件，且不超过20MB',
    image: '只能上传图片文件，且不超过10MB',
    text: '只能上传文本文件，且不超过5MB'
  }
  return tips[form.fileType] || '请上传文件'
}

const handleFileChange = (file: any) => {
  const maxSizeMap: Record<string, number> = {
    pdf: 20 * 1024 * 1024,
    doc: 20 * 1024 * 1024,
    image: 10 * 1024 * 1024,
    text: 5 * 1024 * 1024
  }
  
  const maxSize = maxSizeMap[form.fileType] || 20 * 1024 * 1024
  if (file.raw.size > maxSize) {
    ElMessage.error(`文件大小不能超过 ${maxSize / 1024 / 1024}MB!`)
    return false
  }
  
  form.file = file.raw
  return true
}

const handleFileRemove = () => {
  form.file = null
}

const submitForm = async () => {
  if (!uploadForm.value) return
  
  try {
    await uploadForm.value.validate()
    
    if (!form.file) {
      ElMessage.warning('请先选择要上传的文件')
      return
    }
    
    submitting.value = true
    
    // 构造FormData
    const formData = new FormData()
    formData.append('file', form.file)
    formData.append('title', form.title)
    formData.append('authors', form.authors)
    // 修复：始终添加publicationDate字段，即使为空
    formData.append('publicationDate', form.publicationDate || '')
    formData.append('journal', form.journal)
    formData.append('keywords', form.keywords)
    formData.append('abstractText', form.abstractText)
    formData.append('doi', '') // 添加doi字段，即使为空也要传
    
    // 调用API上传文献
    await literatureApi.upload(formData)
    
    ElMessage.success('文献上传成功!')
    router.push('/literature/list')
    
  } catch (error: any) {
    console.error('Upload error:', error)
    ElMessage.error(error.message || '文献上传失败!')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  uploadForm.value?.resetFields()
  fileList.value = []
  form.file = null
  
  Object.assign(form, {
    title: '',
    authors: '',
    publicationDate: '',
    journal: '',
    keywords: '',
    abstractText: '',
    fileType: 'pdf',
    file: null,
    enableOCR: true,
    enableKeywordExtraction: true,
    enableSummary: true
  })
}

// 生命周期
onMounted(() => {
  // 检查用户类型，如果是管理员则显示提示
  if (userStore.userType === 2) {
    ElMessage.error('管理员不能上传文献')
  }
})
</script>

<style scoped>
.literature-upload {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.header {
  margin-bottom: 20px;
}

.upload-form .form-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.upload-demo {
  width: 100%;
}

.help-text {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.form-actions {
  text-align: center;
  padding: 20px 0;
}

.form-actions .el-button {
  margin: 0 10px;
  min-width: 100px;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style>